#include "http.h"
#include <QFileInfo>

http::http(const QUrl& url,const QString& path,QObject *parent)
    : QObject{parent},m_url(url),m_path(path)
{

}

void http::run()
{
    QEventLoop eventLoop;
    QFile file(m_path);
    if(!file.open(QFile::WriteOnly)){
        qDebug()<<"文件："<<m_path<<"打开失败！";
        return;
    }
    QNetworkAccessManager Manager;
    QNetworkRequest Request(m_url);
    //设置浏览器标识
    Request.setHeader(QNetworkRequest::UserAgentHeader,"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36 Edg/131.0.0.0");
    QNetworkReply* Reply = Manager.get(Request);
    //传递给自身的信号
    connect(Reply,&QNetworkReply::downloadProgress,this,&http::downloadProgress);
    //传递给自身下载
    connect(Reply,&QNetworkReply::downloadProgress,[&](qint64 bytesReceived, qint64 bytesTotal){
        qDebug()<<bytesReceived<<"/"<<bytesTotal;
        file.write(Reply->readAll());
    });
    //传递给自身的完成信号
    connect(Reply,&QNetworkReply::finished,this,&http::finished);
    //传递给自身下载的完成信号
    connect(Reply,&QNetworkReply::finished,[&](){
        QFileInfo info(m_path);
        qDebug()<<"文件："<<info.fileName()<<"下载完成";
        file.close();
        eventLoop.quit();
    });
    eventLoop.exec();
}
































